import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { message } from 'antd';
import { register, sendCode } from '../../api';
import { COMMON_SUCCESS_STATE, LOGIN_PATH } from '../../constant';
import 'antd/lib/message/style';
import './index.less';
import { verifyCode, verifyPassword, verifyPhone, verifyUsername, } from '../../utils/verify';

class RegisterModal extends PureComponent {

  static propTypes = {
    history: PropTypes.object
  };

  state = {
    agreementCheck: false,
    inputObject: {
      username: '',
      phone: '',
      password: '',
      code: '',
    },
    inputVerify: {
      username: '',
      phone: '',
      password: '',
      code: '',
    },
    buttonIsActive: false,
    isClickCode: false,
  };

  // 复选框选中或者取消事件
  change = (event) => {
    const { inputVerify } = this.state;
    const isChecked = event.target.checked;
    this.setState({
      agreementCheck: isChecked,
    });
    //
    if (isChecked) {
      const flag = inputVerify.username &&
        inputVerify.phone &&
        inputVerify.password &&
        inputVerify.code;
      this.setState({ buttonIsActive: flag });
    }
  };

  // 输入框数据事件 受控组件
  input = (type, event) => {
    const { value } = event.target;
    this.setState((state) => {
      const { inputObject } = state;
      inputObject[type] = value;
      return {
        inputObject,
      };
    });
  };

  // 输入框失去焦点事件
  inputBlur = (type) => {
    const {
      inputObject,
      inputVerify
    } = this.state;
    switch (type) {
    case 'username':
      inputVerify[type] = verifyUsername(inputObject.username);
      break;
    case 'phone':
      inputVerify[type] = verifyPhone(inputObject.phone);
      break;
    case 'password':
      inputVerify[type] = verifyPassword(inputObject.password);
      break;
    case 'code':
      inputVerify[type] = verifyCode(inputObject.code);
      break;
    default:
      message.warn('未知警告');
    }

    const otherInputVerify = JSON.parse(JSON.stringify(inputVerify));

    // 设置校验数据
    this.setState({
      inputVerify: otherInputVerify,
    });
  };

  // 提交注册
  submitRegister = async () => {
    const { inputObject } = this.state;
    const {
      code,
      msg
    } = await register(inputObject);
    if (code === COMMON_SUCCESS_STATE) {
      // 跳转登录页面
      this.props.history.replace(LOGIN_PATH);
    } else {
      message.error(msg);
    }
  };

  // 获取验证码
  fetchCode = async (event) => {
    const {
      isClickCode,
      inputVerify: { phone: phone1 },
      inputObject: { phone: phone2 }
    } = this.state;
    if (phone1) {
      if (!isClickCode) {
        this.setState({
          isClickCode: true,
        });
        const { target } = event;
        let time = 60;
        let text = `${time}s后获取`;
        target.innerText = text;
        this.timerId = setInterval(() => {
          if (time <= 0) {
            clearInterval(this.timerId);
            text = '获取验证码';
            target.innerText = text;
            this.setState({
              isClickCode: false,
            });
            return;
          }
          time -= 1;
          text = `${time}s后获取`;
          target.innerText = text;
        }, 1000);

        // 发送请求获取验证码
        const {
          code,
          msg
        } = await sendCode(phone2);
        if (code === COMMON_SUCCESS_STATE) {
          // 请求成功
          message.success(msg);
        } else {
          message.error(msg);
        }
      }
    } else {
      message.warn('请输入正确的手机号');
    }
  };

  render () {
    const {
      agreementCheck,
      inputVerify,
      buttonIsActive,
    } = this.state;
    return (
      <>
        <div className="register_modal">
          <div className="register_modal_desc">
            <h1>欢迎注册</h1>
            <p>
              已有账号？
              <a href="/#">
                登录
              </a>
            </p>
          </div>
          <div className="register_modal_input">
            <div className="register_modal_input_item">
              <div className="register_modal_input_label">
                用户名
              </div>
              <div
                className="register_modal_input_input"
                verify={`${inputVerify.username}`}
              >
                <input
                  onInput={(event) => {
                    this.input('username', event);
                  }}
                  onBlur={() => this.inputBlur('username')}
                  type="text"
                  name="username"
                  placeholder="请输入用户名"
                />
                <p>用户名仅支持中英文、数字和下划线,且不能为纯数字</p>
              </div>
            </div>
            <div className="register_modal_input_item">
              <div className="register_modal_input_label">
                手机号
              </div>
              <div
                className="register_modal_input_input"
                verify={`${inputVerify.phone}`}
              >
                <input
                  onInput={(event) => {
                    this.input('phone', event);
                  }}
                  onBlur={() => this.inputBlur('phone')}
                  type="text"
                  name="phone"
                  placeholder="可用于登录和找回密码"
                />
                <p>手机号码格式不正确</p>
              </div>
            </div>
            <div className="register_modal_input_item">
              <div className="register_modal_input_label">
                密&nbsp;&nbsp;&nbsp;码
              </div>
              <div
                className="register_modal_input_input"
                verify={`${inputVerify.password}`}
              >
                <input
                  onInput={(event) => {
                    this.input('password', event);
                  }}
                  onBlur={() => this.inputBlur('password')}
                  type="password"
                  name="password"
                  placeholder="请设置登录密码"
                />
                <p>密码必须为字母数字下划线包含.并且长度为8-14位</p>
              </div>
            </div>
            <div className="register_modal_input_item">
              <div className="register_modal_input_label">
                验证码
              </div>
              <div
                className="register_modal_input_input"
                verify={`${inputVerify.code}`}
              >
                <input
                  onInput={(event) => {
                    this.input('code', event);
                  }}
                  onBlur={() => this.inputBlur('code')}
                  type="text"
                  placeholder="请输入验证码"
                />
                <button onClick={this.fetchCode}>获取验证码</button>
                <p>请输入验证码，验证码的长度必须为6位</p>
              </div>
            </div>
          </div>
          <div className="register_modal_footer">
            <input
              className={buttonIsActive ? 'active' : ''}
              type="submit"
              value="注册"
              onClick={this.submitRegister}
            />
            <div className="register_agreement">
              <input
                checked={agreementCheck}
                type="checkbox"
                onChange={this.change}
              />
              阅读并接受
              {' '}
              <a href="/#">《百度用户协议》</a>
              及
              <a href="/#">《百度隐私权保护声明》</a>
            </div>
          </div>
        </div>
      </>
    );
  }
}

export default withRouter(RegisterModal);
